
import 'dart:io';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:flutter/material.dart';
import 'package:image_pickers/Media.dart';
import 'package:image_pickers/image_pickers.dart';

import 'xcomment_voice.dart';

class XCommentWidget extends StatefulWidget {

  final Function(bool up) tapOn;
  final String articleId;
  final String rid; // 评论的id
  final FocusNode focusNode;
  final Function(bool isreload) onRefreshData; // 评论完成刷新数据

  _XCommentWidgetState _state;


  XCommentWidget({
    Key key, 
    this.tapOn, 
    this.articleId, 
    this.rid,
    this.focusNode, 
    this.onRefreshData,
  }) : super(key: key);

  requestFocus({String replyname, String rid}){
    _state._requestFocus(name: replyname, id: rid);
  }

  requestFocusReply(String replymoble, String replyname, String rid) { // 回复评论的评论
    _state._requestReplyMobile(replymoble, replyname, rid);
  }

  clear(){
    _state._clear(false); // false 不刷新数据
  }


  @override
  _XCommentWidgetState createState() => _state = _XCommentWidgetState();
}

class _XCommentWidgetState extends State<XCommentWidget> {

  double height = 55.5;
  final normalheight = 55.5;
  bool isvoice = false;
  TextEditingController controller = TextEditingController();

  int imgCount = 0;
  List<File> images = [];
  String voicepath;
  XCommentVoiceWidget _commentVoiceWidget;

  // 回复
  String replyname;
  String rid; // 回复者的名字
  String replymobile;// 回复评论的手机.


  @override
  void initState() {
    super.initState();
    if(widget.rid != null) rid = widget.rid;

    _commentVoiceWidget = XCommentVoiceWidget(minDuraion: 1,onRecordFinish: (path, duration){
      voicepath = path;
    },);
  }

  _requestFocus({String name, String id}) {
    if(name != null) {
      rid = id;
      setState(() {
        replyname = name;
      });
    }

    // 如果没有选中语音状态下点击回复
    if(!isvoice){
      widget.focusNode.requestFocus();
    }
  }

  _requestReplyMobile(String moblie, String name, String id) { // 回复评论的评论
    if(name != null) {
      rid = id;
      replymobile = moblie;
      setState(() {
        replyname = name;
      });
    }

    // 如果没有选中语音状态下点击回复
    if(!isvoice){
      widget.focusNode.requestFocus();
    }
  }

  //从照片选择
  void _album() async {
    List<Media> _listImagePaths = await ImagePickers.pickerPaths(
      galleryMode: GalleryMode.image,
      selectCount: 4 - images.length,
      showCamera: false,
      // cropConfig :CropConfig(enableCrop: true,height: 1,width: 1),
      // compressSize: 500,
    );
    _listImagePaths.forEach((e) { images.add(File(e.path)); });
    setState(() {
      imgCount = images.length;
    });
  }

  void _clear([bool isreload = true]) {
    setState(() {
      imgCount = 0;
      isvoice = false;
      replyname = null;
      height = normalheight;
    });
    controller.clear();
    images.clear();
    if(voicepath != null)File(voicepath).delete();
    voicepath = null;
    _commentVoiceWidget.reset();
    if(widget.onRefreshData != null) widget.onRefreshData(isreload);
  }

  // 发表评论
  _requestComment() {
    if(controller.text == "" && voicepath == null && images.length == 0){
      _clear(false);
      return;
    }
    if(voicepath == null && images.length == 0 && controller.text == "") {
      AlertTool.showToast("请填写内容");
      return;
    }
    
    Map<String, dynamic> params = {};
    if(controller.text != "") {
      params["content"] = controller.text;
    }
    params["aid"] = widget.articleId;
    if(rid != null) {
      params["rid"] = rid;
    }

    if(replymobile != null) {
      params["mobile"] = replymobile;
    }

    Networktool.postArticle(API.articlereply, (data){
      _clear();
      if(data != null) {
        AlertTool.showToast("评论成功");
      }
    }
    ,images: images.length == 0 ? null : images
    ,recordPath: voicepath
    ,params: params
    ,fail: (msg) => AlertTool.showToast(msg)
    );
  }
  
  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;
    return InkWell(
      onTap: (){},
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Container(
            height: imgCount == 0 ? 0 : 95, 
            width: imgCount == 4 ?  size.width - 60 : 95.0 * imgCount, 
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5),
              boxShadow: [
                BoxShadow(blurRadius: 20, color: Colors.black26, spreadRadius: 0)
              ]
            ),
            child: ListView.builder(
              itemCount: imgCount,
              padding: const EdgeInsets.all(2),
              scrollDirection: Axis.horizontal,
              itemBuilder: (context,index){
                return InkWell(
                  onTap: (){
                    setState(() {
                      images.removeAt(index);
                      imgCount = images.length;
                    });
                  },
                  child: Stack(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: PhysicalModel(
                          color: Colors.white,
                          clipBehavior: Clip.antiAlias,
                          borderRadius: BorderRadius.circular(5),
                          child: Image.file(images[index], width: 75, height: 75, fit: BoxFit.cover,),
                        ),
                      ),
                      Positioned(
                        right: 0,
                        top: 0,
                        child: Image.asset("assets/shanchu.png"),
                      )
                    ],
                  ),
                );
              }
            ),
          ),
          Container(
            height: height,
            width: size.width,
            padding: const EdgeInsets.symmetric(vertical: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              border: const Border(top: const BorderSide(width: 0.5, color: APP_divider_color))
            ),
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    GestureDetector(
                      onTap: (){
                        setState(() {
                          isvoice = !isvoice;
                          isvoice ? widget.focusNode.unfocus() : widget.focusNode.requestFocus();
                          height = isvoice ? 200 : normalheight;
                        });
                        if(widget.tapOn != null) widget.tapOn(isvoice);
                      },
                      child: Container(
                        width: 35,
                        height: 30,
                        child: Image.asset(isvoice ? "assets/jianpan.png" : "assets/luyin11.png")
                      ),
                    ),

                    Container(
                      height: 35,
                      width: size.width - 130,
                      padding: const EdgeInsets.only(bottom: 5),
                      child: TextField(
                        autocorrect: false,
                        focusNode: widget.focusNode,
                        controller: controller,
                        maxLines: null,
                        minLines: 1,
                        keyboardType: TextInputType.multiline,
                        onSubmitted: (val){
                          widget.focusNode.unfocus();
                        },
                        decoration: InputDecoration(
                          hintStyle: instanceTextStyle(11, APP_font_grey),
                          hintText: replyname == null ? "说点儿啥吧～" : "回复:$replyname",
                          counterText: "",
                          filled: true,
                          fillColor: APP_scaffold_back_color,
                          contentPadding: const EdgeInsets.symmetric(horizontal: 11.5, vertical: 1),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(const Radius.circular(20)),
                            borderSide: const BorderSide(width: .5, color: APP_divider_color),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(Radius.circular(20)),
                            borderSide: const BorderSide(width: .5, color: APP_divider_color),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(Radius.circular(20)),
                            borderSide: const BorderSide(width: .5, color: APP_divider_color),
                          ),
                        ),
                        onTap: (){
                          setState(() {
                            height = normalheight;
                            isvoice = false;
                          });
                        },
                        onEditingComplete: (){
                          setState(() {
                            height = normalheight;
                          });
                          widget.focusNode.unfocus();
                        },
                      ),
                    ),
                    GestureDetector(
                      onTap: _album,
                      child: Stack(
                        children: [
                          Image.asset("assets/zhaopian1.png", width: 40, height: 30,),
                          Positioned(
                            right: 0,
                            top: 0,
                            child: Offstage(
                              offstage: imgCount == 0,
                              child: Container(
                                width: 15,
                                height: 15,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: Colors.redAccent,
                                  shape: BoxShape.circle
                                ),
                                child: Text(imgCount.toString(), style: instanceTextStyle(9, Colors.white),)
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: _requestComment,
                      child: Container(
                        width: 50,
                        height: 30,
                        alignment: Alignment.center,
                        child: Text("发送", style: instanceTextStyle(14, APP_main_color),)
                      ),
                    )
                  ],
                ),
                Expanded(
                  child: _commentVoiceWidget
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}

